import { getToday, getWeekRange, getCurrentMonth, getTomorrow, isWeekend } from '../../utils/dateUtils';
import { PLAN_STATUS, STORAGE_KEYS } from '../../utils/constants';
import storageService from './storageService';

/**
 * 数据迁移服务 - 处理跨天、跨周、跨月的数据迁移
 */

/**
 * 生成唯一ID
 */
export const generateId = () => {
  return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
};

/**
 * 检查并执行日计划迁移
 * @param {Array} plans - 所有计划列表
 * @param {Object} settings - 用户设置
 * @returns {Array} 迁移后的计划列表
 */
export const migrateDailyPlans = (plans, settings) => {
  const today = getToday();
  const migratedPlans = [...plans];
  
  // 找出今日未完成的日计划
  const pendingDailyPlans = plans.filter(
    plan => plan.type === 'daily' &&
    plan.status === PLAN_STATUS.PENDING &&
    plan.scheduledFor === today
  );

  if (pendingDailyPlans.length === 0) {
    return migratedPlans;
  }

  // 根据设置决定是否自动迁移
  if (settings.autoMigrate) {
    const tomorrow = getTomorrow();
    
    // 如果明天是周末，则不迁移
    if (isWeekend(tomorrow)) {
      return migratedPlans;
    }
    
    pendingDailyPlans.forEach(plan => {
      const index = migratedPlans.findIndex(p => p.id === plan.id);
      if (index !== -1) {
        // 创建新计划到明天
        const newPlan = {
          ...plan,
          id: generateId(),
          scheduledFor: tomorrow,
          status: PLAN_STATUS.PENDING,
          createdAt: new Date().toISOString(),
          parentId: plan.id, // 记录原始计划ID
        };
        
        // 更新原计划状态为已迁移
        migratedPlans[index] = {
          ...migratedPlans[index],
          status: PLAN_STATUS.MIGRATED,
        };
        
        migratedPlans.push(newPlan);
      }
    });
  }

  return migratedPlans;
};

/**
 * 检查并执行周计划迁移
 * @param {Array} weeklyPlans - 周计划列表
 * @param {string} weekStartDay - 周起始日
 * @returns {Array} 迁移后的周计划列表
 */
export const migrateWeeklyPlans = (weeklyPlans, weekStartDay) => {
  const today = getToday();
  const currentWeek = getWeekRange(new Date(today), weekStartDay);
  
  // 检查是否有未完成的周计划需要处理
  const pendingWeeklyPlans = weeklyPlans.filter(
    plan => plan.weekEnd < currentWeek.weekStart && plan.completionRate < 100
  );

  // 可以在这里添加周计划迁移逻辑
  // 目前先返回原列表
  return weeklyPlans;
};

/**
 * 检查并执行月计划迁移
 * @param {Array} monthlyPlans - 月计划列表
 * @returns {Array} 迁移后的月计划列表
 */
export const migrateMonthlyPlans = (monthlyPlans) => {
  const currentMonth = getCurrentMonth();
  
  // 检查是否有未完成的月计划
  const pendingMonthlyPlans = monthlyPlans.filter(
    plan => plan.month < currentMonth && plan.completionRate < 100
  );

  // 可以在这里添加月计划迁移逻辑
  // 目前先返回原列表
  return monthlyPlans;
};

/**
 * 检查并执行年度清理（每年1月1日）
 * @returns {boolean} 是否执行了清理
 */
export const checkAndPerformAnnualCleanup = async () => {
  try {
    const today = getToday();
    const todayDate = new Date(today);
    const month = todayDate.getMonth() + 1; // 0-11 -> 1-12
    const day = todayDate.getDate();
    
    // 检查是否是1月1日
    if (month === 1 && day === 1) {
      // 检查是否已经执行过今年的清理
      const lastCleanupKey = '@PlanFlow:lastAnnualCleanup';
      const lastCleanupResult = await storageService.load(lastCleanupKey);
      const lastCleanupYear = lastCleanupResult.data;
      const currentYear = todayDate.getFullYear();
      
      // 如果今年还没有执行过清理，则执行
      if (lastCleanupYear !== currentYear) {
        // 清空所有计划数据
        await storageService.remove(STORAGE_KEYS.PLANS);
        await storageService.remove(STORAGE_KEYS.WEEKLY_PLANS);
        await storageService.remove(STORAGE_KEYS.MONTHLY_PLANS);
        await storageService.remove(STORAGE_KEYS.STATISTICS);
        
        // 记录本次清理的年份
        await storageService.save(lastCleanupKey, currentYear);
        
        return true;
      }
    }
    
    return false;
  } catch (error) {
    console.error('Annual cleanup error:', error);
    return false;
  }
};

/**
 * 执行所有数据迁移
 * @param {Object} data - 所有数据
 * @param {Object} settings - 用户设置
 * @returns {Object} 迁移后的数据
 */
export const migrateAllData = (data, settings) => {
  const { plans = [], weeklyPlans = [], monthlyPlans = [] } = data;
  
  return {
    plans: migrateDailyPlans(plans, settings),
    weeklyPlans: migrateWeeklyPlans(weeklyPlans, settings.weekStartDay),
    monthlyPlans: migrateMonthlyPlans(monthlyPlans),
  };
};

